package com.github.thinwonton.activemq.showcase.sample.helloworld.topic;

import com.github.thinwonton.activemq.showcase.sample.utils.ActiveMQManager;

import javax.jms.*;
import java.io.IOException;

public class Subscriber1 {
    public static void main(String[] args) throws IOException {
        System.out.println("Subscriber1 started!");

        try {
            //获取连接
            Connection connection = ActiveMQManager.createConnection();

            //启动连接
            connection.start();

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            //建立话题
            Topic topic = session.createTopic(Producer.TOPIC_NAME);

            //建立消费者
            MessageConsumer consumer = session.createConsumer(topic);

            //监听消息
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    try {
                        TextMessage textMessage = (TextMessage) message;
                        String text = textMessage.getText();
                        System.out.println("Subscriber1 获取消息 ---->" + text);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });

            // 线程一直等待
            System.in.read();

            consumer.close();
            session.close();
            connection.stop();

        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Subscriber1 end!");
    }
}
